<template>
  <!-- 做保养 -->
  <view class="container" @touchstart="touch.touchstart" @touchmove="touch.touchmove" @touchend="touch.touchend">
    <page-loading :show="showPage">
    <u-navbar title=" ">
      <view class="navbar-content">
        <view class="title-box" :style="{transform: `translateX(-${opacity === 1 ? logoOffset : 0}px)`}">
          <i-icon icon="iconLOGO" size="40rpx"></i-icon>
          <text class="title" :style="{opacity: opacity === 1 ? 0 : 1}">做保养</text>
        </view>
      </view>
    </u-navbar>
    
    <!-- 车辆信息 -->
    <view class="car-info-box" v-if="myLoveCar">
      <view class="car-info" @click="onChangeCar">
        <image class="logo" :src="`https://files.yzsheng.com/goodimg/brandimg/${myLoveCar.brand_Id}.png`" mode=""></image>
        <view class="info">
          <view class="title">
            <text class="text car-title">{{myLoveCar.brand_Name}}-{{myLoveCar.car_Type_Name}}</text>
            <text class="record" @click.stop="onClickMaintenanceRecord">保养记录</text>
          </view>
          <!-- <view class="title fixed" v-show="opacity === 1" 
          :style="{
            left: titlePosition.left + 'px',
            top:titlePosition.top + 'px',
          }"> -->
          <view class="title fixed1" v-if="opacity === 1">
            <text class="text">{{myLoveCar.brand_Name}}-{{myLoveCar.car_Type_Name}}</text>
            <u-icon name="arrow-right" color="#999"></u-icon>
          </view>
          <view class="model"><text>{{myLoveCar.car_Name}}</text></view>
        </view>
      </view>
      <view class="input-box">
        <view class="cell">
          <text class="title">行驶里程</text>
          <view class="input">
            <u-input type="number" v-model="value" placeholder="点击输入里程" @confirm="confirm" :disabled="from === 'intelligence'" />
            <text class="unit">km</text>
          </view>
        </view>
        <view class="cell">
          <text class="title">上路时间</text>
          <view class="input">
            <u-input v-model="value1" type="text" placeholder="点击选择上路时间" disabled @click="onClicTime" />
          </view>
        </view>
      </view>
    </view>
    
    <view v-else class="top flex flex-jc-c flex-dir-c default" style="height: 160rpx;position: relative;">
    	<image src="https://files.yzsheng.com/client/index/carMaintenance/tianjiaqiche.png" style="width: 199rpx;height: 91rpx;position: absolute;bottom: 33rpx;right: 40rpx;"></image>
    	<view style="color: #666666;">添加爱车，提供精准适配服务</view>
    	<view class="add" @click="onClickAddCar">添加爱车<u-icon name="arrow-right"></u-icon></view>
    </view>
    
    <!-- 自助洗车入口 -->
    <self-wash-entry bottom="20rpx" />
    
    <!-- 会员有礼 -->
    <!-- <view class="join-member">
      <image class="logo" src="https://files.yzsheng.com/client/weixin/logo.png"></image>
      <view class="text-box">
        <text class="title">7迈养车会员PRO</text>
        <text class="desc">养车更省</text>
      </view>
      <view class="btn"><text>入会有礼</text></view>
    </view> -->
    <!--  -->
    <view class="img-wrap">
      <!-- <image class="img" src="https://files.yzsheng.com/goodimg/factoryimg/3661_factory_41.png!idx"></image> -->
      <view class="text" v-if="keyword && !hasSearchResult">
        <text>搜索“{{keyword}}”无结果，您可以自行选择下列需要的服务项目</text>
      </view> 
    </view>
    
    <!-- 优惠券 -->
    <view class="sticky"></view>
    <view style="height: 92rpx;" v-show="isSticky && couponList.length > 0"></view>
    <view class="coupon-box" :class="{fixed: isSticky}" v-if="couponList.length > 0" :style="{right: couponList.length > 0 ? 0 : '565rpx'}">
      <!-- <view class="select-service"><text>选择服务</text></view> -->
      <view class="coupon" v-if="couponList.length > 0">
        <text class="title">优惠券:</text>
        <view class="coupon-list">
          <view class="cell" v-for="(item, index) in couponList" :key="index" @click="onClickCoupon(item)"><text>{{item.coupon_name}}</text></view>
        </view>
      </view>
    </view>
    
    <view class="content">
      <view style="width: 185rpx;height: 1rpx;" v-show="isSticky"></view>
      <!-- 左边分类 -->
      <view class="left-menu" :class="{fixed: isSticky && couponList.length > 0,'fixed1': isSticky && couponList.length < 1,'no-coupon': couponList.length < 1}">
        <scroll-view :scroll-y="isSticky" class="scroll-view" :scroll-into-view="'menu' + serviceActive">
          <view 
            :id="'menu' + index"
            class="cell" 
            v-for="(item, index) in serviceList" 
            :key="index" 
            :class="{active: index === serviceActive}"
            @click="onClickLeftMenu(item, index)"
            :style="{height: 100 / serviceList.length + '%'}"
            >
            <text>{{item.title}}</text>
            <text class="badge" v-if="serviceListSelectNum[index] > 0">{{serviceListSelectNum[index]}}</text>
          </view>
        </scroll-view>
      </view>
      
      <!-- 左右商品列表 -->
      <view class="service-list">
        <view
          v-for="(item, index) in list"
          :key="index"
          class="right-item"
          :class="'right-item-' + index"
        >
          <!-- <view style="height: 20rpx;" v-if="index === 0"></view> -->
          
          <view class="service-title-box">
            <view class="bg" :class="{animate: currentTab === index}"></view>
            <view class="service-title">
              <text>{{item.maintenance_Type_Name}}{{item.maintenance_Type_Name === '洗车' ? '(车身冲洗、除污，内饰清洁、除尘)' : ''}}</text>
            </view>
          </view>
          
          <!-- 各个服务列表 -->
          <view class="serve-list">
            <!-- 
              洗车，显示这一块布局的内容
              通过has_Children字段，判断是否有children列表
             -->
            <template v-if="!item.has_Children">
              <view class="serve-item">
                <!-- 服务的卡片布局 -->
                <view
                  v-for="serItem in item.maintenanceGoodsLists"
                  :key="serItem.id"
                  class="serve-item-card flex"
                >
                  <!-- 服务图片 -->
                  <view class="img-box u-skeleton-fillet">
                    <u-image
                      :src="serItem.pic_URL || errorImg"
                      width="100"
                      height="100"
                      border-radius="10"
                      mode="widthFix"
                      class="img"
                      :error-icon="errorImg"
                    ></u-image>
                  </view>
          
                  <view class="right-content">
                    <!-- 服务名称 -->
                    <view class="name color-666 font-24 font-bold">
                      <text class="m-line-text-2 u-skeleton-fillet">{{
                        serItem.goods_Name
                      }}</text>
                    </view>
          
                    <!-- 服务价格 -->
                    <view class="price-box flex flex-jc-sb flex-ai-fe">
                      <view class="price-text font-24 u-skeleton-fillet">
                        <text class="color-EB5C02 font-bold"
                          >￥<text class="font-32">{{
                            serItem.sale_Price
                          }}</text></text
                        >
                        <text class="color-999 serve-fee"
                          v-if="serItem.original_Price > 0">￥{{ serItem.original_Price }}</text
                        >
                      </view>
          
                      <!-- 计数器 -->
                      <view class="num-box flex flex-ai-c u-skeleton-fillet">
                        <view
                          v-if="serItem.amount !== 0"
                          class="btn less"
                          @click="less(serItem, item)"
                          ><u-icon name="minus" size="20" color="#3d3d3d" /></view
                        >
                        <input
                          v-show="serItem.amount !== 0"
                          type="number"
                          v-model="serItem.amount"
                          class="cont"
                          disabled
                        />
                        <view class="btn add" @click="add(serItem, item)"
                          ><u-icon name="plus" size="24" color="#3d3d3d" /></view
                        >
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </template>
          
            <!-- 其他服务显示这一块布局内容 -->
            <template v-else>
              <view
                v-for="serItem in item.maintenanceTypeAndGoodsChildList"
                :key="serItem.id"
                class="serve-item"
              >
                <view class="serve-item-radio">
                  <!-- 是套餐，就可勾选单选 -->
                  <label
                    v-if="item.showMulSelected"
                    class="radio-box"
                    @click="selectedServe(serItem, item)"
                  >
                    <view class="icon-radio flex flex-ai-c flex-jc-sb">
                      <text class="font-28 color-333">
                        {{ serItem.maintenance_Type_Name }}
                      </text>
                      <i-icon
                        v-show="!serItem.isChecked"
                        icon="icontuoyuan"
                        size="36rpx"
                        color="#999"
                      ></i-icon>
                      <i-icon
                        v-show="serItem.isChecked"
                        icon="iconiconfontxuanzhong"
                        size="36rpx"
                        color="#78B015"
                      ></i-icon>
                    </view>
                  </label>
          
                  <!-- 不是套餐，直接显示标题 -->
                  <view v-else class="title">
                    {{ serItem.maintenance_Type_Name }}
                  </view>
          
                  <!-- 没有勾选按钮的服务的卡片布局 显示 -->
                  <view v-if="!item.showMulSelected">
                    <view
                      v-for="serItemSub in serItem.maintenanceGoodsLists"
                      :key="serItemSub.id"
                      class="serve-item-card flex"
                    >
                      <!-- 服务图片 -->
                      <view class="img-box">
                        <u-image
                          :src="serItemSub.pic_URL || errorImg"
                          width="100"
                          height="100"
                          border-radius="10"
                          mode="widthFix"
                          class="img"
                          :error-icon="errorImg"
                        ></u-image>
                      </view>
          
                      <view class="right-content">
                        <!-- 服务名称 -->
                        <view class="name color-666 font-24 font-bold">
                          <text class="m-line-text-2">
                            {{ serItemSub.goods_Name }}
                          </text>
                        </view>
          
                        <!-- 服务价格 -->
                        <view class="price-box flex flex-jc-sb flex-ai-fe">
                          <view class="price-text font-24">
                            <text class="color-EB5C02 font-bold">
                              ￥
                              <text class="font-32">
                                {{ serItemSub.sale_Price }}
                              </text>
                            </text>
                            <text class="color-999 serve-fee" v-if="serItemSub.original_Price > 0">
                              ￥{{ serItemSub.original_Price }}
                            </text>
                          </view>
          
                          <!-- 计数器 -->
                          <view class="num-box flex flex-ai-c">
                            <view
                              v-if="serItemSub.amount !== 0"
                              class="btn less"
                              @click="less(serItemSub)"
                              ><u-icon name="minus" size="20" color="#3d3d3d" /></view
                            >
                            <input
                              v-show="serItemSub.amount !== 0"
                              type="number"
                              v-model="serItemSub.amount"
                              class="cont"
                              disabled
                            />
                            <view class="btn add" @click="add(serItemSub, item)"
                              ><u-icon name="plus" size="24" color="#3d3d3d" /></view
                            >
                          </view>
                        </view>
                      </view>
                    </view>
                  </view>
          
                  <!-- 有勾选按钮的服务的卡片布局 显示 -->
                  <view v-else>
                    <view
                      v-for="(serItemSub, k) in serItem.maintenanceGoodsLists"
                      :key="k"
                      class="serve-item-card flex"
                    >
                      <!-- 服务图片 -->
                      <view class="img-box">
                        <u-image
                          :src="serItemSub.pic_URL || errorImg"
                          width="100"
                          height="100"
                          border-radius="10"
                          mode="widthFix"
                          class="img"
                          :error-icon="errorImg"
                        ></u-image>
                      </view>
          
                      <view class="right-content">
                        <!-- 服务名称 -->
                        <view class="name color-666 font-24 font-bold">
                          <text class="m-line-text-2">
                            {{ serItemSub.goods_Name }}
                          </text>
                          <text class="change" @click="onChangeGoods(serItemSub, item)" v-if="!serItemSub.isVisualGoods">变更</text>
                        </view>
          
                        <!-- 服务价格 -->
                        <view class="price-box flex flex-jc-sb flex-ai-fe">
                          <view class="price-text font-24">
                            <text class="color-EB5C02 font-bold">
                              ￥
                              <text class="font-32">
                                {{ serItemSub.sale_Price }}
                              </text>
                            </text>
                            <text class="color-999 serve-fee" v-if="serItemSub.original_Price > 0">
                              ￥{{ serItemSub.original_Price }}
                            </text>
                          </view>
          
                          <!-- 计数器 -->
                          <view class="num-box flex flex-ai-c" v-if="item.maintenance_Type_Name != '小保养' && item.maintenance_Type_Name != '大保养'">
                            <view
                              v-if="serItemSub.amount !== 0"
                              class="btn less"
                              @click="less(serItemSub)"
                              ><u-icon name="minus" size="20" color="#3d3d3d" /></view>
                            <input
                              v-show="serItemSub.amount !== 0"
                              type="number"
                              v-model="serItemSub.amount"
                              class="cont"
                              disabled
                            />
                            <view class="btn add" @click="add(serItemSub, item)"
                              ><u-icon name="plus" size="24" color="#3d3d3d" /></view>
                          </view>
                          <view class="num-box flex flex-ai-c" v-else><text v-show="serItemSub.amount !== 0">x{{serItemSub.amount}}</text></view>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </template>
          </view>
          
        </view>
      </view>
    </view>
    
    <view class="float-btn">
      <image class="img" src="https://files.yzsheng.com/client/commodity/fuligou.png" @click="onJumpWelfare"></image>
    </view>
    
    <footer-bar :cart-list="cartList" :my-love-car="myLoveCar" @onChangeNum="onChangeNum" />
    </page-loading>
    <u-picker mode="time" :params="params" v-model="show" @confirm="confirm" :end-year="maxTime"></u-picker>
  </view>
</template>

<script module="touch" lang="wxs">
function setStyle(ins, data) {
  ins.selectComponent('.float-btn').setStyle(data)
}
function touchstart(event, ins) {
}

function touchend(event, ins) {
  setStyle(ins, {
    'right': '10rpx',
    'opacity': '1'
  })
}

function touchmove(event, ins) {
  setStyle(ins, {
    'right': '-80rpx',
    'opacity': '.5'
  })
}
module.exports = {
  touchend: touchend,
  touchstart: touchstart,
  touchmove: touchmove
}
</script>

<script>
import footerBar from './components/footerBar.vue'
import selfWashEntry from '@/components/selfWash/selfWashEntry'
const dayjs = require('@/utils/dayjs.js')
import maintenance from '@/utils/maintenance.js'
export default {
  components: {
    footerBar,
    selfWashEntry
  },
  mixins: [maintenance],
  data() {
    return {
      opacity: 0, // 透明度
      logoOffset: 0,
      titleInitPosition: null,
      titlePosition: {
        top: 0,
        left: 0,
        width: 0
      },
      value: '',
      value1: '',
      params: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false
      },
      show: false,
      contentHeight: 0,
      navHeight: 0,
      isSticky: false,
      serviceActive: 0,
      serviceList: [],
      list: [],
      checkedList: [], // 选中值的列表
      cartList: [] ,// 购物车列表
      scrollTop: 0,
      keyword: '',
      hasSearchResult: false,
      carId: '', // 车辆id
      myLoveCar: null,// 我的爱车
      myLoveCarIndex: 0,// 我的爱车下标
      userinfo: uni.getStorageSync('Ztc_C_USER_INFO') || null,
      anchor: -1, // 锚点
      from: '', // 页面来源
      maxTime: dayjs().year(),
      couponList: [], // 优惠券
      specifAll: {
        brandlist: null, //品牌
        Serieslist: null, //系列
        Displacement: null, //排量
        Modelyear: null, //年款
        Configulists: null, //车子
      },
      index: -1,
      renderStatus: false,
      addCarStataus: false,
      errorImg: 'https://files.yzsheng.com/client/index/carMaintenance/default.png',
      showPage: false,
      isLogin: true
    }
  },
  computed: {
    serviceListSelectNum() {
      let num = this.list.map(item => {
        return item.serCount
      })
      return num
    },
    maintenanceCategory() {
      return this.$store.state.maintenanceCategory
    }
  },
  onLoad(option) {
    
    let {screenHeight, statusBarHeight} = uni.getSystemInfoSync()
    this.navHeight = statusBarHeight + 44
    this.contentHeight = screenHeight - statusBarHeight - 44
    
    // 搜索关键词
    this.keyword = option.keyword ? decodeURIComponent(option.keyword) : ''
    
    // 车辆id
    this.carId = option.carId || ''
    
    // 锚点
    this.anchor = option.index || -1
    this.index = this.anchor
    
    // 里程数
    this.value = option.mileage || ''
    // 上路时间
    this.value1 = option.time || ''
    // 来源
    this.from = option.from || ''
    
    // 监听替换商品
    uni.$on('maintenanceReplaceProduct', (data) => {
      if(data) {
        this.replaceProduct(data)
      }
    })
    
    // 选择品牌，系列，排量，年款，车子
    uni.$on('doMaintenance', data => {
      Object.assign(this.specifAll, data)
      if (data.licenseplate && data.pageFrom === 'doMaintenance') {
        this.addCarStataus = true
        this.addCar(this.specifAll)
      }
    })
    
    uni.$on('changeMyLoveCar', data => {
      let oldId = this.myLoveCar.car_Id
      this.myLoveCar = data
      if(data.car_Id !== oldId) {
        setTimeout(() => {
          this.getList()
        }, 300)
      }
    })
    
    if(this.userinfo) {
      this.getLoveCar(() => {
        if(this.myLoveCar){
          this.addCarStataus = true
          this.getMyCouponList()
          this.getList()
        } else {
          uni.navigateTo({
            url: '/pages_common/addYourCar/addYourCar?type=120&pageFrom=doMaintenance'
          })
        }
      })
    } else {
      uni.navigateTo({
        url: '/pages_logins/login/login',
        success: () => {
          setTimeout(() => {
            this.isLogin = false
          }, 300)
        }
      })
    }
  },
  onShow() {
    if(this.renderStatus && !this.addCarStataus) {
      uni.navigateBack({
        delta: 1
      })
    }
    if(!this.isLogin && !uni.getStorageSync('Ztc_C_USER_INFO')) {
      uni.navigateBack({
        delta: 1
      })
    } else if(!this.isLogin && uni.getStorageSync('Ztc_C_USER_INFO') && !this.renderStatus) {
      this.userinfo = uni.getStorageSync('Ztc_C_USER_INFO')
      this.renderStatus = true
      this.getLoveCar(() => {
        if(this.myLoveCar){
          this.addCarStataus = true
          this.getMyCouponList()
          this.getList()
        } else {
          uni.navigateTo({
            url: '/pages_common/addYourCar/addYourCar?type=120&pageFrom=doMaintenance'
          })
        }
      })
    }
  },
  onReady() {
    this.renderStatus = true
  },
  methods: {
    // 页面滚动
    pageScroll(scrollTop) {
      if(!this.myLoveCar || !this.titleInitPosition) return false
      let left = uni.upx2px(750) / 2 - uni.upx2px(170)
      if (scrollTop < 100) {
        this.opacity = scrollTop / 100
        this.logoOffset = left - (left - left * this.opacity)
        
        this.titlePosition.top = (this.titleInitPosition.top - this.titleInitPosition.top * this.opacity)
        this.titlePosition.left = this.titleInitPosition.left + (this.titleInitPosition.width * this.opacity)
      } else if (scrollTop > 100) {
        this.opacity = 1;
        // #ifdef MP
         this.logoOffset = left - (uni.getMenuButtonBoundingClientRect().width / 2)
        // #endif
        // #ifndef MP
        this.logoOffset = left
        // #endif
        this.titlePosition.top = 0
        this.titlePosition.left = this.titleInitPosition.left + this.titleInitPosition.width
      } else {
        this.opacity = 1;
      }
    },
    
    async confirm(data) {
      if(typeof data === 'object') {
        let {year, month, day} = data
        let time = `${year}-${month}-${day}`
        let current = dayjs().format('YYYY-MM-DD')
        if(dayjs(current).diff(time, 'day') >= 0) {
          this.value1 = time
        } else {
          uni.showToast({
            icon: 'none',
            title: '上路时间不能大于当前时间'
          })
          this.value1 = ''
          return false
        }
      }
      if(this.value && this.value1) {
        uni.showLoading({
          title: '加载中'
        })
        try{
          let res = await this.$api.maintenanceOrder.GetDoMaintenanceResponses({
            km: Number(this.value),
            months: dayjs().diff(dayjs(this.value1), 'month')
          })
          uni.hideLoading()
          if(res.code === 200) {
            let arr = res.data.map(item => {
              return item.maintenance_Type_Id
            })
            this.$store.commit('maintenanceCategory', {
              ids: arr,
              data: res.data
            })
            if(arr.length > 0) {
              this.searchMaintenanceCategory()
            }
          } else {
            uni.showToast({
              icon: 'none',
              title: data.msg
            })
          }
        }catch(e){
          uni.hideLoading()
        }
      }
    },
    // 获取列表数据
    async getList() {
      if(this.list.length > 0) {
        uni.showLoading({
          title: '加载中',
          mask: true
        })
      }
      try {
        this.dataKey = 1
        // const res = await this.$api.jsonData.MaintenanceTypeAndGoods()
        const res = await this.$api.maintenanceIndex.GetMaintenanceTypeAndGoodsList({
          configuration_Id: `${this.myLoveCar.car_Id}`
        })
        res.data = {
          data: res.data
        }
        // 添加勾选字段
        res.data.data.forEach(item => {
          item.serCount = 0
          if (item.has_Children && item.showMulSelected) {
            if(item.maintenance_Type_Name === '小保养' || item.maintenance_Type_Name === '大保养') {
              let arr = []
              item.maintenanceTypeAndGoodsChildList.forEach(ser => {
                ser.maintenanceGoodsLists.forEach(serItem => {
                  arr.push(serItem)
                })
              })
              let temp = item.maintenanceTypeAndGoodsChildList[0]
              temp.id = item.id
              temp.maintenanceGoodsLists = arr
              temp.maintenance_Type_Name = item.maintenance_Type_Name + '服务'
              item.maintenanceTypeAndGoodsChildList = [temp]
            } else {
              item.maintenanceTypeAndGoodsChildList.forEach(ser => {
                ser.isChecked = false
              })
            }
          } else if (item.has_Children && !item.showMulSelected) {
            item.maintenanceTypeAndGoodsChildList.forEach(ser => {
              ser.showMulSelected = false
            })
          }
        })
        this.serviceList = res.data.data.map(item => {
          return {
            num: 0,
            title: item.maintenance_Type_Name,
            id: item.id,
            offsetTop: 0
          }
        })
        uni.hideLoading()
    
        let cartList = this.$u.deepClone(this.cartList)
        let arr = []
        this.cartList = []
        cartList.map(item => {
          item.maintenanceGoodsLists.map(i => {
            arr.push(i)
          })
        })
    
        this.handleAddAmount(res.data.data, arr) // 递归给服务项添加数量字段
        this.showPage = true
        this.list = res.data.data
        // 获取布局信息
        this.$nextTick(() => {
          setTimeout(() => {
            this.handleCheckLength()
            this.getViewRect()
            this.elementInView(this.scrollTop)
            // 搜索
            if(this.keyword) {
              this.searchKeyWord()
            }
            // 如果有需要保养的类别 则自动加上
            if(this.maintenanceCategory) {
              this.searchMaintenanceCategory()
            }
    
            // 如果有锚点 则自动添加
            if(this.index > 1) {
              this.searchAnchor()
            }
    
            if(this.from === 'intelligence') {
              this.confirm()
            }
    
          }, 500)
        })
      } catch (err) {
        uni.hideLoading()
        console.log(err)
      }
    },
    onClicTime(){
      if(this.from === 'intelligence') return false
      this.show = true
    },
    // 搜索
    searchKeyWord(){
      let key = this.keyword
      let index = 0
      let hasResult = false
      this.list.map((item, idx) => {
        if(!hasResult) {
          if(item.maintenance_Type_Name.indexOf(key) > -1) {
            index = idx
            hasResult = true
          } else if (item.has_Children && item.showMulSelected) {
            item.maintenanceTypeAndGoodsChildList.forEach((ser) => {
              if(ser.maintenanceGoodsLists) {
                ser.maintenanceGoodsLists.forEach(serItem =>{
                  if(serItem.goods_Name.indexOf(key) > -1) {
                    index = idx
                    hasResult = true
                  }
                })
              }
            })
          } else if(item.has_Children && !item.showMulSelected) {
            item.maintenanceTypeAndGoodsChildList.forEach((ser) => {
              ser.maintenanceGoodsLists.forEach(serItem =>{
                if(serItem.goods_Name.indexOf(key) > -1) {
                  index = idx
                  hasResult = true
                }
              })
            })
          } else {
            item.maintenanceGoodsLists.map((ser) => {
              if(ser.goods_Name.indexOf(key) > -1) {
                index = idx
                hasResult = true
              }
            })
          }
        }
      })
      this.hasSearchResult = hasResult
      if(hasResult) {
        setTimeout(() => {
          console.log(111)
          this.serviceActive = index
          uni.pageScrollTo({
            duration: 0,
            scrollTop: this.serviceList[index].offsetTop - 139
          })
        }, 300)
      }
    },
    // 匹配保养类目
    searchMaintenanceCategory(){
      let data = this.maintenanceCategory
      let arr = data.ids
      this.list.map((item, idx) => {
        if(arr.indexOf(item.id) > -1) {
          if (item.has_Children && item.showMulSelected) {
            item.maintenanceTypeAndGoodsChildList.forEach((ser) => {
              ser.isChecked = true
              ser.maintenanceGoodsLists.forEach((i, k) => {
                i.amount = 1
              })
            })
          }
        } else {
          if (item.has_Children && item.showMulSelected) {
            item.maintenanceTypeAndGoodsChildList.forEach((ser) => {
              if(arr.indexOf(ser.id) > -1) {
                ser.isChecked = true
              } else {
                ser.isChecked = false
              }
              ser.maintenanceGoodsLists.map(i => {
                i.amount = ser.isChecked ? 1 : 0
              })
            })
          }
        }
      })
      this.handleCheckLength(true)
    },
    // 获取爱车信息
    async getLoveCar(callback) {
      try{
        let res = await this.$api.commodity.GetCarList({
          uid: this.userinfo.id
        })
        if(res.code === 200) {
          if(this.carId) {
            res.data.list.map((item, index) => {
              if(item.id === this.carId) {
                this.myLoveCar = item
                this.myLoveCarIndex = index
              }
            })
          } else {
            this.myLoveCar = res.data.list[0]
            this.myLoveCarIndex = 0
          }
          callback && callback()
          if(this.myLoveCar) {
            this.$nextTick(() =>{
              uni.createSelectorQuery().in(this).select('.car-title').boundingClientRect((rect)=> {
                let {left, top, width} = rect
                width = (uni.getSystemInfoSync().screenWidth - width) / 2 - left
                this.titleInitPosition = {
                  left,
                  top,
                  width
                }
                this.titlePosition = {
                  left,
                  top: this.scrollTop + top
                }
              }).exec()
              
              if(this.serviceList.length > 0) {
                let t = setTimeout(() => {
                  this.getViewRect()
                  clearTimeout(t)
                }, 200)
              }
              
            })
          }
        }
        this.loading = false
        // uni.hideLoading()
      }catch(e){
        this.loading = false
        // uni.hideLoading()
      }
    },
    // 保养记录
    onClickMaintenanceRecord() {
      uni.navigateTo({
        url: '/pages_commodity/mylovecarInformation/mylovecarInformation?index=' + this.myLoveCarIndex + '&current=1&state=3'
      })
    },
    // 获取已有优惠券
    getMyCouponList() {
      try{
        uni.getStorage({
          key: 'Ztc_C_USER_INFO',
          success: async data => {
            let res = await this.$api.user.GetCouponList({
              coupon_class: 2,
              pageIndex: 1,
              pageSize: 3,
              mobile: data.data.mobile
            })
            if(res.code === 200 && res.data.list.length > 0) {
              this.couponList = res.data.list
            }
          }
        })
      }catch(e){
        //TODO handle the exception
      }
    },
    // 添加爱车
    async addCar(data) {
      try{
        uni.showLoading({
          title: '加载中'
        })
        let res = await this.$api.common.AddCar({
          uid: this.userinfo.id,
          brand_Id: data.brandlist.bid,
          brand_Name: data.brandlist.brand,
          car_Type_Id: data.Serieslist.carTypeId,
          car_Type_Name: data.Serieslist.carTypeName,
          car_Id: data.Configulist.id,
          car_Name: data.Configulist.name,
          displacement: data.Displacement.pName,
          yeartype: data.Configulist.date,
          car_Num: data.licenseplate, //车牌号
        })
        uni.hideLoading()
        this.getLoveCar(() => {
          if(this.addCarStataus) {
            this.getMyCouponList()
            this.getList()
          }
        })
      }catch(e){
        uni.hideLoading()
      }
    },
    // 点击添加爱车
    onClickAddCar() {
      if(uni.getStorageSync('token') && uni.getStorageSync('token') !== '') {
        uni.navigateTo({
          url: '/pages_common/addYourCar/addYourCar?type=120&pageFrom=doMaintenance'
        })
      } else {
        uni.setStorageSync('launchFlag', false)
        uni.navigateTo({
          url: '/pages_logins/login/login'
        })
      }
    },
    // 点击选择爱车
    onChangeCar() {
      uni.navigateTo({
        url: '/pages_common/myLoveCarList/myLoveCarList'
      })
    },
    // 点击优惠券
    onClickCoupon(data) {
      if(!data.is_Package) {
        uni.navigateTo({
          url: `/pages_userModule/myCoupon/detail?id=${data.id}`
        })
        this.$store.commit('couponInfo', data)
      } else {
        uni.navigateTo({
          url: `/pages_userModule/myCoupon/setMealDetail?id=${data.id}`
        })
      }
    },
    // 匹配锚点项目并勾选
    searchAnchor(){
      this.list.map((item, idx) => {
        if(idx === Number(this.index)) {
          if (item.has_Children && item.showMulSelected) {
            item.maintenanceTypeAndGoodsChildList.forEach(ser => {
              ser.isChecked = true
              ser.maintenanceGoodsLists.forEach(serItem => {
                serItem.amount = 1
              })
            })
          } else if(item.has_Children && !item.showMulSelected) {
            item.maintenanceTypeAndGoodsChildList.forEach(ser => {
              ser.maintenanceGoodsLists.forEach(serItem => {
                serItem.amount = 1
              })
            })
          } else {
            item.maintenanceGoodsLists.map(ser => {
              ser.amount = 1
            })
          }
          this.handleCheckLength()
        }
      })
    },
    // 跳转福利购
    onJumpWelfare() {
      uni.navigateTo({
        url: '/pages_buy_index/welfareDetails/welfareDetails'
      })
    }
  },
  // #ifdef H5
  activated () {
    window.addEventListener('scroll', this.h5Pagescroll)
  },
  deactivated() {
    window.removeEventListener('scroll', this.h5Pagescroll)
  },
  // #endif
  onPageScroll(e) {
    this.scrollTop = e.scrollTop
    this.pageScroll(e.scrollTop)
    this.elementInView(e.scrollTop)
    this.$u.getRect('.sticky').then(data => {
      this.isSticky = data.top <= this.navHeight 
    })
  },
  onUnload() {
    uni.$off('maintenanceReplaceProduct')
    uni.$off('changeMyLoveCar')
    uni.$off('doMaintenance')
    this.$store.commit('maintenanceCategory', null)
  }
}
</script>

<style lang="scss">
page{
  background-color: #f1f1f1;
}
.container{
  overflow: hidden;
  min-height: 100vh;
  .navbar-content{
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    box-sizing: border-box;
    padding-right: 68rpx;
    .title-box{
      display: flex;
      align-items: center;
      justify-content: center;
      .title{
        color: #333;
        font-size: 36rpx;
        margin-left: 22rpx;
      }
    }
  }
  .car-info-box{
    background-color: #fff;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.12);
    border-radius: 10rpx;
    margin: 24rpx;
    .car-info{
      display: flex;
      padding: 35rpx 25rpx;
      .logo{
        width: 90rpx;
        height: 90rpx;
      }
      .info{
        margin-left: 35rpx;
        flex: 1;
        .title{
          display: flex;
          justify-content: space-between;
          .text{
            font-size: 34rpx;
            color: #333;
            font-weight: bold;
            display: block;
            flex: 1;
            margin-right: 20rpx;
          }
          .record{
            font-size: 28rpx;
            color: #FBB000;
            font-weight: bold;
            line-height: 44rpx;
          }
        }
        .fixed{
          position: fixed;
          z-index: 999;
          display: flex;
          align-items: center;
          box-sizing: border-box;
          height: calc(44px + var(--status-bar-height));
          padding-top: var(--status-bar-height);
        }
        .fixed1{
          position: fixed;
          z-index: 999;
          display: flex;
          align-items: center;
          box-sizing: border-box;
          /* #ifndef MP */
          height: calc(44px + var(--status-bar-height));
          /* #endif */
          /* #ifdef MP */
          height: calc(38px + var(--status-bar-height));
          /* #endif */
          padding-top: var(--status-bar-height);
          top: 0;
          left: 50%;
          transform: translateX(-50%);
        }
        .model{
          font-size: 28rpx;
          color: #666;
          margin-top: 6rpx;
        }
      }
    }
    .input-box{
      display: flex;
      align-items: center;
      padding: 20rpx 0;
      .cell{
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        padding: 0 50rpx;
        .title{
          font-size: 28rpx;
          color: #666;
        }
        .input{
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      .line{
        width: 2rpx;
        height: 74rpx;
        background-color: #eee;
      }
    }
  }
  .join-member{
    background-color: #fff;
    box-shadow: 0 0 10rpx 0 rgba(0, 0, 0, 0.12);
    border-radius: 10rpx;
    margin: 24rpx;
    padding: 30rpx;
    display: flex;
    align-items: center;
    .logo{
      width: 110rpx;
      height: 110rpx;
      border-radius: 5rpx;
    }
    .text-box{
      display: flex;
      flex-direction: column;
      margin: 0 20rpx;
      flex: 1;
      .title{
        font-size: 32rpx;
        color: #333;
        font-weight: bold;
      }
      .desc{
        font-size: 28rpx;
        color: #999;
        margin-top: 14rpx;
      }
    }
    .btn{
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 26rpx;
      color: #333;
      width: 150rpx;
      height: 54rpx;
      background: linear-gradient(0deg, #FBD220, #FFE23E);
      border-radius: 27rpx;
    }
  }
  .img-wrap{
    background-color: #fff;
    padding: 0 24rpx 0;
    overflow: hidden;
    .img{
      width: 100%;
      height: 220rpx;
      display: block;
      border-radius: 10rpx;
      margin-top: 24rpx;
    }
    .text{
      font-size: 28rpx;
      color: #666;
      padding: 14rpx 6rpx;
    }
  }
  .coupon-box{
    padding: 20rpx 0;
    display: flex;
    align-items: center;
    background-color: #fff;
    .select-service{
      height: 50rpx;
      width: 185rpx;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      color: #333;
      border-right: 2rpx solid #DBDBDB;
    }
    .coupon{
      flex: 1;
      margin-left: 25rpx;
      display: flex;
      align-items: center;
      .title{
        color: #999;
        font-size: 32rpx;
      }
      .coupon-list{
        display: flex;
        align-items: center;
        .cell{
          // background-color: #FF4B44;
          height: 42rpx;
          display: flex;
          align-items: center;
          padding: 0 20rpx;
          margin-left: 18rpx;
          font-size: 18rpx;
          color: #fff;
          background-image: 
            radial-gradient(
              circle at 100% 3px, 
              transparent 4rpx, 
              #FF4B44 4rpx, 
              #FF4B44 0rpx);
          background-size: 100% 6px;
          background-repeat-x: no-repeat;
          position: relative;
          &::after{
            content: '';
            display: block;
            width: 8px;
            height: 8px;
            border-radius: 8px;
            background-color: #fff;
            position: absolute;
            left: 0;
            top: 50%;
            margin: -4px 0 0 -4px;
          }
          &::before{
            content: '';
            display: block;
            width: 1px;
            height: 42px;
            background-color: #fff;
            position: absolute;
            right: 0;
            top: 0;
          }
        }
      }
    }
    &.fixed{
      position: fixed;
      left: 0;
      top: calc(var(--status-bar-height) + 44px);
      z-index: 9;
      right: 0;
    }
  }
  .content{
    overflow: hidden;
    display: flex;
    .left-menu{
      width: 185rpx;
      overflow: hidden;
      height: calc(100vh - var(--status-bar-height) - 44px - 92rpx);
      box-sizing: border-box;
      background-color: #f1f1f1;
      padding-bottom: 110rpx;
      padding-bottom: calc(constant(safe-area-inset-bottom) + 110rpx);
      padding-bottom: calc(env(safe-area-inset-bottom) + 110rpx);
      &.no-coupon{
        height: calc(100vh - var(--status-bar-height) - 44px);
      }
      .scroll-view{
        height: 100%;
      }
      .cell{
        height: 110rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        color: #999;
        text-align: center;
        line-height: 44rpx;
        position: relative;
        .badge{
          display: block;
          min-width: 34rpx;
          height: 34rpx;
          line-height: 34rpx;
          background-color: #FF4B44;
          font-size: 20rpx;
          color: #fff;
          border-radius: 34rpx;
          position: absolute;
          right: 12rpx;
          top: 6rpx;
          box-sizing: border-box;
          padding: 0 10rpx;
          text-align: center;
        }
        &.active{
          background-color: #fff;
          color: #333;
          font-weight: bold;
        }
      }
      &.fixed{
        position: fixed;
        left: 0;
        top: calc(var(--status-bar-height) + 44px + 84rpx);
      }
      &.fixed1{
        position: fixed;
        left: 0;
        top: calc(var(--status-bar-height) + 44px);
      }
    }
    .service-list{
      flex: 1;
      background-color: #fff;
      box-sizing: border-box;
      padding-bottom: 110rpx;
      padding-bottom: calc(constant(safe-area-inset-bottom) + 110rpx);
      padding-bottom: calc(env(safe-area-inset-bottom) + 110rpx);
      .right-item{
        .tips{
          text-align: center;
          font-size: 24rpx;
          color: #B8B8B8;
        }
      }
      .service-title-box{
        background-color: #F1F1F1;
        height: 64rpx;
        position: relative;
        overflow: hidden;
        .bg{
          position: absolute;
          left: -120rpx;
          height: 64rpx;
          top: -60rpx;
          background-color: #fff;
          width: 30rpx;
          height: 200rpx;
          transform: rotate(-45deg);
          box-shadow: 0 0 30rpx 30rpx #fff;
        }
        .animate{
          animation: titleHight 1s infinite;
        }
      }
      .service-title{
        height: 64rpx;
        display: flex;
        align-items: center;
        padding: 0 24rpx;
        color: #666;
        font-size: 24rpx;
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
      }
    }
    // 服务列表
    .serve-list {
      .serve-item {
        .serve-item-radio {
          padding: 20rpx 24rpx;
          .title{
            font-size: 28rpx;
            color: #333;
          }
        }
      }
    
      // 服务卡片布局样式
      .serve-item-card {
        padding: 20rpx 0;
    
        // 服务图片
        .img-box {
          width: 100rpx;
          height: 100rpx;
          border-radius: 10rpx;
          overflow: hidden;
    
          .img {
            width: 100%;
            height: 100%;
          }
        }
    
        // 右边内容
        .right-content {
          flex: 1;
          padding-left: 15rpx;
          .name{
            display: flex;
            align-items: center;
            .m-line-text-2{
              display: block;
              flex: 1;
              color: #333;
            }
            .change{
              font-size: 24rpx;
              color: #799CF2;
              margin-left: 30rpx;
            }
          }
        }
    
        // 价格部分
        .price-box {
          margin-top: 24rpx;
    
          // 原价，中间有删除横线
          .serve-fee {
            margin-left: 10rpx;
            text-decoration: line-through;
          }
        }
    
        // 计数器
        .num-box {
          height: 40rpx;
    
          .btn {
            width: 36rpx;
            height: 36rpx;
            text-align: center;
            font-size: 40rpx;
            color: #3d3d3d;
            border-radius: 8rpx;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          .cont {
            width: 40rpx;
            height: 40rpx;
            margin: 0 16rpx;
            border-radius: 10rpx;
            text-align: center;
            font-size: 24rpx;
            font-weight: bold;
          }
          // 减号
          .less {
            border: 1px solid #ffe23e;
          }
          // 加号
          .add {
            background: #ffe23e;
          }
        }
      }
    }
  }
  .font-bold{
    font-weight: bold;
  }
  .color-EB5C02 {
    color: #FF4B44;
  }
  
  .top{
    padding: 35rpx 25rpx;
    margin: 25rpx 25rpx 0;
    background-color: #fff;
    box-shadow: 0 0 10rpx 0 rgba(0, 0, 0, 0.12);
    border-radius: 10rpx;
    .top-main{
    	flex: 1;
    }
    
    .top-title{
    	width: 400rpx;
    	margin-left: 35rpx;
    	font-size: 28rpx;
    	font-weight: 500;
    	color: #666666;
    	
    	.pz{
    		display: -webkit-box;
    		overflow: hidden;
    		white-space: normal !important;
    		text-overflow: ellipsis;
    		word-wrap: break-word;
    		-webkit-line-clamp: 1;
    		-webkit-box-orient: vertical;
    	}
    	view:first-child{
    		font-size: 34rpx;
    		display: -webkit-box;
    		overflow: hidden;
    		white-space: normal !important;
    		text-overflow: ellipsis;
    		word-wrap: break-word;
    		-webkit-line-clamp: 2;
    		-webkit-box-orient: vertical;
    		font-weight: bold;
    		color: #333333;
    	}
    }
    
    
    .maintain{
    	color: #3D3D3D;
    	font-weight: 500;
    	width: 163rpx;
    	height: 54rpx;
    	background: linear-gradient(0deg, #FBD220, #FFE23E);
    	border-radius: 27rpx;
    	text-align: center;
    	line-height: 54rpx;
    }
    .top-logo{
    	margin-left: 25rpx;
    	width: 90rpx;
    	height: 90rpx;
    }
    .default{
      padding: 0 42rpx;
      margin: 24rpx;
      background-color: #fff;
      box-shadow: 0 0 10rpx 0 rgba(0, 0, 0, 0.12);
      border-radius: 10rpx;
    }
    .add{
      width: 200rpx;
      height: 60rpx;
      background: linear-gradient(0deg, #FBD220, #FFE23E);
      border-radius: 30px;
      font-size: 28rpx;
      font-weight: bold;
      color: #3D3D3D;
      text-align: center;
      line-height: 60rpx;
      margin-top: 20rpx;
    }
  }
  .float-btn{
    position: fixed;
    width: 116rpx;
    height: 116rpx;
    right: 10rpx;
    bottom: 200rpx;
    bottom: calc(constant(safe-area-inset-bottom) + 200rpx);
    bottom: calc(env(safe-area-inset-bottom) + 200rpx);
    transition: all .3s;
    .img{
      width: 100%;
      height: 100%;
    }
  }
}
@keyframes titleHight {
  0% {
    left: -120rpx;
    opacity: 1;
  }
  100% {
    left: 150%;
    opacity: .2;
  }
}
</style>
